package app.contatos.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import app.contatos.MainActivity;
import app.contatos.R;

public class GruposActivity extends Activity {

	private GridView grid = null;
	
	static final int[] icones = {
		R.drawable.ic_launcher_grupo_amigos,
		R.drawable.ic_launcher_grupo_trabalho,
		R.drawable.ic_launcher_grupo_conhecidos,
		R.drawable.ic_launcher_grupo_familia
	};
	public static final String _GRUPO = "contatos.app._GRUPO";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.grupos);
		carregar();
		configurar();
	}
	
	private void configurar() {
		grid.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				irPara(MainActivity.class, String.valueOf(position));
			}
		});
	}
	
	public void irPara(Class<?> clazz, String id) {
    	Intent intent = new Intent(GruposActivity.this, clazz);
    	if (id != null) {
    		intent.putExtra(_GRUPO, id);
    	}
    	startActivity(intent);
    }

	private void carregar() {
		grid = (GridView) findViewById(R.id.gridView1);
		grid.setAdapter(new IconeAdapter(getBaseContext()));
	}
	
	static class IconeAdapter extends BaseAdapter {

		private Context context;
		
		public IconeAdapter(Context context) {
			super();
			this.context = context;
		}
		
		static class GruposHolder {
			public ImageView icone;
			public TextView texto;
		}

		public int getCount() {
			return icones.length;
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			GruposHolder holder = null;
			View v = convertView;
			if (v == null) {
				LayoutInflater inflater = 
						(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.grupos_item, null);
				holder = new GruposHolder();
				holder.texto = (TextView) v.findViewById(R.id.tv_texto);
				holder.icone = (ImageView) v.findViewById(R.id.iv_icone);
				v.setTag(holder);
			} else {
				holder = (GruposHolder) v.getTag();
			}
			holder.icone.setImageResource(icones[position]);
			holder.texto.setText(context.getResources()
					.getStringArray(R.array.array_grupos)[position]);
			return v;
		}
	}
}
